package com.whales.lms.rms.scheduler.task;

import javax.inject.Inject;

import org.springframework.stereotype.Component;

import com.whales.lms.rms.scheduler.TaskTemplate;
import com.whales.lms.rms.scheduler.service.IFService;
import com.whales.lms.rms.web.model.FaultVO;
import com.whales.lms.rms.web.model.ScheduleVO;
import com.whales.lms.rms.web.service.FaultService;
import com.whales.lms.rms.web.service.ScheduleService;
import com.whales.lms.rms.web.util.ConstantUtil;
import com.whales.shared.util.CalendarUtil;

/**
 * System(PC) On/Off Scheduler
 * PC turn on은 WakeOnLan API를 사용.
 * PC turn off는 Agent에 PCOFF 명령을 호출하여 사용.
 * @author sw775.park
 *
 */
@Component
public class SystemOnOffTask extends TaskTemplate {
	@Inject
	private ScheduleService scheduleService;
	@Inject
	private IFService ifService;
	@Inject
	private FaultService faultService;
	
	public SystemOnOffTask(){
		this.setConExpression("0 0/10 * * * ?"); //10분 간격
	}
	
	@Override
	public void execute() throws Exception {
		String currentTime = CalendarUtil.getDateFormat("HH:mm");
		this.turnOnPc(currentTime);
		this.turnOffPc(currentTime);
	}
	
	public void turnOnPc(String time) throws Exception{
		ScheduleVO scheduleVO = new ScheduleVO();
		scheduleVO.setStartTime(time);
		for(ScheduleVO turnOnPc : scheduleService.getTurnOnOffPcListByTime(scheduleVO)){
			String result = ConstantUtil.STATE_OKE;
			if(!ConstantUtil.STATE_OKE.equals(ifService.pcOn(turnOnPc.getIp(), turnOnPc.getMacAddress()))){
				result = ConstantUtil.STATE_HNE;
			}
			FaultVO faultVO = new FaultVO();
			faultVO.setIp(turnOnPc.getIp());
			faultVO.setSepType(ConstantUtil.TYPE_HW);
			faultVO.setFaultCode(result);
//			faultService.create(faultVO);
		}
	}
	
	public void turnOffPc(String time) throws Exception{
		ScheduleVO scheduleVO = new ScheduleVO();
		scheduleVO.setEndTime(time);
		for(ScheduleVO turnOffPc : scheduleService.getTurnOnOffPcListByTime(scheduleVO)){
			String result = ConstantUtil.STATE_OKE;
			if(!ConstantUtil.STATE_OKE.equals(ifService.pcOff(turnOffPc.getIp()))){
				result = ConstantUtil.STATE_HNE;
			}
			FaultVO faultVO = new FaultVO();
			faultVO.setIp(turnOffPc.getIp());
			faultVO.setSepType(ConstantUtil.TYPE_HW);
			faultVO.setFaultCode(result);
//			faultService.create(faultVO);
		}
	}
}
